/**
 * ConnectionChecker.java
 * 11 mai 2010 22:53:30
 * Copyright Julien 2010
 */
package fr.jbrunet.win.ndriveconnector;

import org.apache.log4j.Logger;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;

import fr.jbrunet.logger.JLog;
import fr.jbrunet.win.gui.ndriveconnector.windows.MainWindow;
import fr.jbrunet.win.ndriveconnector.config.Config;
import fr.jbrunet.win.ndriveconnector.utils.Connection;
import fr.jbrunet.win.ndriveconnector.utils.Constants;

/**
 * @author Julien
 *
 */
public class ConnectionChecker extends Thread{
	private static final Logger log = JLog.getLogger(ConnectionChecker.class);
	private static Config config = null;

	private static Shell shell = null;
	private static ProgressBar cxProgressBar = null;

	private boolean stop = false;

	/**
	 * @throws Exception 
	 * 
	 */
	public ConnectionChecker(Shell theShell) throws Exception {
		shell = theShell;
		config = Config.getInstance();
	}

	public void run() {
		log.debug("Starting ConnectionChecker thread");

		//Get the progress bar
		shell.getDisplay().syncExec(new Runnable() {
			public void run() {
				try {
					MainWindow window = MainWindow.getInstance();
					cxProgressBar = window.getCxTryProgress();
					window.setConnectionStatus(Constants.STATUS_NOT_CONNECTED);
				} catch (Exception e) {
					log.fatal(e);
				}				
			}
		});	

		boolean firstTry = true;
		int waitingTime = config.getCheckIntervalDisconnected(); 
		try {
			while(!stop) { //always run

				if ( firstTry ) { //No connection Try yet
					firstTry = false;
					//First connection try
					log.debug("First connection try");
					if ( Connection.getInstance().getStatus()!=Constants.STATUS_CONNECTED ) {
						new ConnectionTry(shell, cxProgressBar).start();						
					}
				} else {
					//update waiting time
					if ( Connection.getInstance().getStatus() == Constants.STATUS_CONNECTED ) {
						waitingTime = config.getCheckIntervalConnected();
					}
					else {
						waitingTime = config.getCheckIntervalDisconnected(); ;
					}
					
					log.debug("Sleeping for " + waitingTime/1000 + " secondes..."); 
					sleep(waitingTime);
					
					if (Connection.getInstance().getStatus()!=Constants.STATUS_CONNECTION_IN_PROGRESS) { //if connectionTry not already running
						log.debug("Connection checker launching new connection try");
						new ConnectionTry(shell, cxProgressBar).start();
						//ConnectionTry.getInstance(shell, cxProgressBar).tryToConnect();
					}
				}
			}
		}
		catch (Exception e) {
			log.error("Error in ConnectionChecker thread",e);
		}
		finally {
			log.debug("End of ConnectionChecker thread");
		}
	}
}
